package com.luyu.util;

import com.luyu.entity.User;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;


public class UserContextUtil {

    public static  SecurityContext getSecurityContext(){
        return SecurityContextHolder.getContext();
    }

    public  static User getUserContext(){
        return (User) getData(()->getSecurityContext(),(context)-> context.getAuthentication().getPrincipal());
    }

    public  static Long getUserCurrentRoleId(){
       return getData(()->getUserContext(),(user -> user.getCurrentRoleId()));
    }

    public  static String getUserName(){
        return getData(()->getUserContext(),(user -> user.getName()));

    }



    public  static List<Long> getUserAllRoleId() {
        return getData(()->getUserContext(),(user -> user.getRoleIds()));
    }

    public static<T,R> R  getData(Supplier<T> t,Function<T,R> function){
        T param = t.get();
        if (param== null) {
            return null;
        }
        return function.apply(param);
    }


}
